package models;

import java.util.*;
import javax.persistence.*;

import play.Logger;
import play.db.ebean.*;
import play.data.format.*;
import play.data.validation.*;

import controllers.MD5Hash;

/**
 * User entity managed by Ebean
 */
@Entity
@Table(name="Enduser")
public class User extends Model {

	@Id
    @Constraints.Required
    @Formats.NonEmpty
    public String username;

    @Formats.NonEmpty
    @Constraints.Required
    public String password;

	public String email;
	public String credit_card;
	public int points;
	public int role;

	public User(String username, String password, String email, String credit_card, int role) {
		this.username = username;
		this.password = password;
		this.email = email;
		this.credit_card = credit_card;
		
		this.points = 0;
		this.role = 0;
	}
	
	
	
    // -- Queries

    public static Model.Finder<String,User> find = new Model.Finder(String.class, User.class);

    /**
     * Retrieve all users.
     */
    public static List<User> findAll() {
        return find.all();
    }

    /**
     * Retrieve a User from username.
     */
    public static User findByUser(String user) {
        return find.where().eq("username", user).findUnique();
    }

    /**
     * Authenticate a User.
     */
    public static User authenticate(String username, String password) {
        return find.where()
            .eq("username", username)
            .eq("password", MD5Hash.digest(password))
            .findUnique();
    }

	/**
	 * Check if a certain username already exists in the database
	 */
	
	public static boolean isUsernameExists(String username)
	{
		return (find.where().eq("username", username).findRowCount() > 0);
	}
	
    // --

    public String toString() {
        return "User(" + username + ")";
    }

}

